define(["angularAMD","moment"], function (angularAMD,moment) {
    angularAMD.service('G0104Service', ['$rootScope', '$filter', '$translate', 'config', 'MMWService', '$mdDialog', "$calculater", "$mddProvider",
        function ($rootScope, $filter, $translate, config, $MMWService, $mdDialog, $calculater, $mddProvider){
            this.init = function(machine, plot, parent, feedback){
                var mode = 'trackOut';
                var tmpAbnormal_qty = 0;

                var tmpBadReason = [];
                var badCodeList = {};
                var badReasonInfo = [];

                var plotInfo = {}; // plot.info.get
                var badReasonInfo_backup = [],//不良原因備份
                    labor_detail_backup = [],//多人產量備份
                    production_inf_detail_backup = [],
                    machine_no = 'N/A',//生產資訊備份
                    record_eqp = plot.record_eqp || 'N';//是否紀錄生產設備及機時

                //取得生產批資料
                var getInitInfo = function () {
                    var content = {
                        machine_no : machine_no, //machine_no,
                        plot_no: plot.plot_no,
                        op_seq : '',//
                        op_no :plot.op_no,
                        sub_op_no: plot.sub_op_no,
                        workstation_no:'',//
                        qty: '',
                        return_type:'5' // 報完工
                    };
                    if(parent == 'B0214'){
                        content.mode = '1';
                    }
                    $MMWService.sendToServer({
                        uri: 'ServicesSTD.Module_WIP.plot_info_get',
                            // $mddProvider.Getfunc('G0104Service', 'plot_info_get'),
                        content : content,
                        success : function(data){
                            if(data.plot_info_get.length > 0){
                                plotInfo = data.plot_info_get[0];
                                if(plotInfo.workstation_detail[0].labor_detail.length == 0){
                                    $rootScope.showAlert($filter('translate')('G0104.showAlert.column7'));
                                } else {
                                    plotInfo.report_datetime = new Date();
                                    plotInfo.qty = plotInfo.workstation_detail[0].check_out_qty;
                                    plotInfo.good_qty = plotInfo.workstation_detail[0].check_out_qty;
                                    //計算不良原因總數
                                    plotInfo.total_abnormal_qty = 0;//報廢
                                    plotInfo.total_lack_qty = 0;//短少
                                    plotInfo.total_surplus_qty = 0;//多餘
                                    //人員計價 總額 初始化 add by a991241234 for M# 70310 
                                    plotInfo.price_sum = "";
                                    for(var i in plotInfo.workstation_detail[0].labor_detail)
                                    {
                                        plotInfo.workstation_detail[0].labor_detail[i].price_sum ="";
                                    }
                                    if(plotInfo.workstation_detail[0].abnormal_detail){
                                        plotInfo.workstation_detail[0].abnormal_detail.forEach(function(abnormal_detail){
                                            if(abnormal_detail.abnormal_type == '11'){
                                                plotInfo.total_surplus_qty  = $calculater.decimalAdd((+plotInfo.total_surplus_qty), (+abnormal_detail.defect_qty));
                                            } else if(abnormal_detail.abnormal_type == '12'){
                                                plotInfo.total_lack_qty  = $calculater.decimalAdd((+plotInfo.total_lack_qty), (+abnormal_detail.defect_qty));
                                            } else {
                                                plotInfo.total_abnormal_qty = $calculater.decimalAdd((+plotInfo.total_abnormal_qty), (+abnormal_detail.defect_qty));
                                            }
                                        });
                                    }
                                    //2018051601 modify by Dustdusk for M#45925:
                                    //良品數 = 『出站數量』 - 『不良品』 - 『短少』 + 『多餘』
                                    plotInfo.good_qty =  $calculater.decimalSub($calculater.decimalSub($calculater.decimalAdd((+plotInfo.good_qty), (+plotInfo.total_surplus_qty)), (+plotInfo.total_abnormal_qty)), (+plotInfo.total_lack_qty));
                                    if(!plotInfo.workstation_detail[0].machine_qty||plotInfo.workstation_detail[0].machine_qty==''){
                                        plotInfo.workstation_detail[0].machine_qty = 1;
                                    }
                                    //2018051601 modify by Dustdusk for M#45925:
                                    //物料使用量 = 『良品』 + 『不良品』 + 『短少』 = 『出站數量』 + 『多餘』
                                    var sum_qty = $calculater.decimalAdd((+plotInfo.qty),(+plotInfo.total_surplus_qty));
                                    for(var i=0; i<plotInfo.workstation_detail[0].materials_detail.length; i++){
                                        plotInfo.workstation_detail[0].materials_detail[i].use_qty = $calculater.decimalMutiple(sum_qty, plotInfo.workstation_detail[0].materials_detail[i].std_use_qty, 6);
                                    }

                                    //多人產量登入
                                    for(var i=0; i<plotInfo.workstation_detail[0].labor_detail.length; i++){
                                        plotInfo.workstation_detail[0].labor_detail[i].qty = plotInfo.qty ;
                                    }
                                    //plotInfo.workstation_detail[0].QTYACIO = plotInfo.qty *((+plotInfo.workstation_detail[0].C_Numerator)/(+plotInfo.workstation_detail[0].C_Denominator));

                                    // 子作業
                                    plotInfo.sub_op_no = plot.sub_op_no;
                                    plotInfo.sub_op_name = plot.sub_op_name;

                                    // 機時
                                    if(record_eqp == 'Y'){
                                        plotInfo.workstation_detail[0].machine_hours = plotInfo.workstation_detail[0].labor_hours;
                                    }
                                    //人員計價 出站 總額計算 add by a991241234 for M# 70310 
                                    getPriceSum();
                                    getPriceSumByLabor();
                                    openDialog(plotInfo);
                                }
                            } else {
                                $rootScope.showAlert('plot_info_get is empty');
                            }
                        }
                    });
                };

                //回到出站畫面
                function backToTrackOut(dialog){
                    if(dialog.mode == 'badReason'){
                        dialog.badReasonInfo = badReasonInfo_backup.slice();
                        badReasonInfo_backup = [];

                        dialog.tmpBadReason = '';
                        dialog.tmpAbnormal_qty = '';
                    } else if(dialog.mode == 'multiple'){
                        dialog.plotInfo.workstation_detail[0].labor_detail = angular.merge([],labor_detail_backup);
                        labor_detail_backup = [];
                        dialog.tmpLabor_no = '';
                    } else if(dialog.mode == 'production_inf'){
                        dialog.plotInfo.production_inf_detail = angular.merge([],production_inf_detail_backup);
                        production_inf_detail_backup = [];
                    }
                    dialog.mode='trackOut';
                }
                //人員計價 出站 總額計算 add by a991241234 for M# 70310 
                function getPriceSum()
                {
                    var price_check_1 = isNaN(parseInt(plotInfo.price_type)) == false;
                    var price_check_2 = isNaN(parseFloat(plotInfo.price)) == false;
                    
                    if(price_check_1 && price_check_2)
                    {
                        switch(plotInfo.price_type)
                        {
                            //計件
                            case "0":
                                if(isNaN(parseFloat(plotInfo.qty)) == false)
                                plotInfo.price_sum = parseFloat(plotInfo.qty) * parseFloat(plotInfo.price);
                            break;
                            //計時
                            case "1":
                                if(isNaN(parseFloat(plotInfo.workstation_detail[0].labor_hours)) == false)
                                plotInfo.price_sum = parseFloat(plotInfo.workstation_detail[0].labor_hours) * parseFloat(plotInfo.price);
                            break;
                        }
                        console.log(plotInfo.price_sum);
                    }
                }
                //人員計價 多人量產 總額計算 add by a991241234 for M# 70310 
                function getPriceSumByLabor()
                {
                    //console.log(plotInfo.workstation_detail[0].labor_detail);
                    var price_check_1 = isNaN(parseInt(plotInfo.price_type)) == false;
                    var price_check_2 = isNaN(parseFloat(plotInfo.price)) == false;
                    var price_check_3 = plotInfo.workstation_detail[0].labor_detail.length > 0;
                    if(price_check_1 && price_check_2 && price_check_3)
                    {
                        switch(plotInfo.price_type)
                        {
                            //計件
                            case "0":
                                var sum = 0;
                                for(var i in plotInfo.workstation_detail[0].labor_detail)
                                {
                                    var qty;
                                    if(isNaN(parseFloat(plotInfo.workstation_detail[0].labor_detail[i].qty)) == false)
                                        qty = plotInfo.workstation_detail[0].labor_detail[i].qty;
                                    else
                                        qty = plotInfo.workstation_detail[0].labor_detail[i].labor_qty;
                                    plotInfo.workstation_detail[0].labor_detail[i].price_sum = parseFloat(plotInfo.price) * parseFloat(qty);
                                    sum +=plotInfo.workstation_detail[0].labor_detail[i].price_sum;
                                }
                                if(sum > 0)
                                    plotInfo.price_sum = sum.toFixed(2);
                            break;
                            //計時    
                            case "1":
                                var sum = 0;
                                for(var i in plotInfo.workstation_detail[0].labor_detail)
                                {
                                    var time = plotInfo.workstation_detail[0].labor_detail[i].labor_time;
                                    plotInfo.workstation_detail[0].labor_detail[i].price_sum = parseFloat(plotInfo.price) * parseFloat(time);
                                    sum +=plotInfo.workstation_detail[0].labor_detail[i].price_sum;
                                }
                                if(sum > 0)
                                    plotInfo.price_sum = sum.toFixed(2);
                            break;
                        }
                    }
                }
                //出站確認
                function trackOutConfirm(dialog) {
                    // 20211112 modify by Alan for #0101888 :[sMES]子作業重複報工需控卡[寶齡]
                    // 新增時間檢查，確保報工時不重複
                    var nowTime;
                    var orgTime = dialog.plotInfo.workstation_detail[0].labor_hours;
                    var content = {
                        machine_no : machine_no, //machine_no,
                        plot_no: plot.plot_no,
                        op_seq : '',//
                        op_no :plot.op_no,
                        sub_op_no: plot.sub_op_no,
                        workstation_no:'',//
                        qty: '',
                        return_type:'5' // 報完工
                    };
                    $MMWService.sendToServer({
                        uri: 'ServicesSTD.Module_WIP.plot_info_get',
                            // $mddProvider.Getfunc('G0104Service', 'plot_info_get'),
                        content: content,
                        success: function (data) {
                            nowTime = data.plot_info_get[0].workstation_detail[0].labor_hours;
                            if (orgTime === 0) {
                                $rootScope.showAlert($filter('translate')('G0104.msg.labor_hours_equal_zero'));
                                return
                            }
                            if (nowTime < orgTime) {
                                $rootScope.showAlert($filter('translate')('G0104.msg.report_duplicate'));
                                return
                            } else {
                                var abnormal_detail = [],
                                    plot_info_detail= {},
                                    materials_detail=[],
                                    subop_employee_detail=[];

                                dialog.badReasonInfo.forEach(function (item) {
                                    abnormal_detail.push({
                                        reason_type:item.abnormal_type,
                                        abnormal_no:item.abnormal_no,
                                        defect_qty:item.defect_qty
                                    });
                                });

                                if(dialog.parent != 'B0214'){
                                    dialog.plotInfo.workstation_detail[0].labor_detail.forEach(function(item){
                                        subop_employee_detail.push({
                                            employee_no:item.labor_no,
                                            work_time:item.labor_time,
                                            qty:item.qty
                                        });
                                    });
                                }

                                dialog.plotInfo.workstation_detail[0].materials_detail.forEach(function(item){
                                    if(item.putinplace_type == '5')
                                        return;

                                    materials_detail.push({
                                        materials_no:item.materials_no,
                                        materials_plot_no:item.materials_plot_no,
                                        actual_use_qty:item.use_qty,

                                    });
                                });
                                //人員計價 add by a991241234 for M# 70310
                                var price_rate_list = [];
                                for (var i in dialog.plotInfo.workstation_detail[0].labor_detail)
                                {
                                    var price_rate_obj = {};
                                    price_rate_obj.acc = dialog.plotInfo.workstation_detail[0].labor_detail[i].labor_no;
                                    price_rate_obj.price_rate = dialog.plotInfo.workstation_detail[0].labor_detail[i].PriceRate;
                                    price_rate_list.push(price_rate_obj);
                                }
                                plot_info_detail = {
                                    report_datetime : dialog.plotInfo.sysdate_time,
                                    machine_no : machine_no, //
                                    plot_no : dialog.plotInfo.workstation_detail[0].plot_no,
                                    op_seq : dialog.plotInfo.workstation_detail[0].op_seq,
                                    op_no : dialog.plotInfo.workstation_detail[0].op_no,
                                    sub_op_no: dialog.plotInfo.sub_op_no,
                                    workstation_no : '',
                                    qty:dialog.plotInfo.qty,//20180418 modify by Dustdusk for 調整回傳數量，一律改為使用者輸入的數量
                                    labor_hours : dialog.plotInfo.workstation_detail[0].labor_hours,
                                    machine_hours : dialog.plotInfo.workstation_detail[0].machine_hours,
                                    number_of_operators : dialog.plotInfo.workstation_detail[0].number_of_labor,//
                                    plot_stamp : dialog.plotInfo.workstation_detail[0].plot_stamp,
                                    machine_no_wip : dialog.plotInfo.machine_no_wip, //下拉選擇的設備編號
                                    abnormal_detail : abnormal_detail,
                                    subop_employee_detail : subop_employee_detail,
                                    materials_detail : materials_detail,
                                    wait_reason_detail : dialog.plotInfo.wait_reason_detail,
                                    //add by a991241234 for M# 70310 人員計價
                                    price:dialog.plotInfo.price,
                                    price_type:dialog.plotInfo.price_type,
                                    price_rate_list:price_rate_list

                                };

                                var content = {
                                    report_datetime: plot_info_detail.report_datetime,
                                    check_out_mode: '1', //1. 預設模式
                                    check_out_type: '1', //1. 報完工
                                    plot_info_detail:[plot_info_detail],
                                    production_inf_type : dialog.plotInfo.production_inf_type,
                                    production_inf_detail:dialog.plotInfo.production_inf_detail
                                };

                                $MMWService.sendToServer({
                                    uri: 'ServicesSTD.Module_WIP.subop_report_process',
                                        // $mddProvider.Getfunc('G0104Service', 'subop_report_process'),
                                    content: content,
                                    success: function (data, response) {
                                        $rootScope.showToast(response.Message); //報完工成功
                                        dialog.hide();
                                        if(feedback)
                                            feedback();
                                    }
                                });
                            }
                        }
                    });
                }

                //檢查出站資訊
                function ProductionParametersCheckProcess(dialog){
                    var defect_qty = 0;
                    dialog.badReasonInfo.forEach(function (item) {
                        if(item.abnormal_type != '11'){
                            //2018051601 modify by Dustdusk for M#45925: 調整良品不良品計算規則
                            defect_qty = defect_qty + (+item.defect_qty);
                        }
                    });
                    var content = {
                        handle_type : 'CHECK_OUT',
                        recordlist : [{
                            plot_no : dialog.plotInfo.workstation_detail[0].plot_no,
                            op_no : dialog.plotInfo.workstation_detail[0].op_no,
                            qty : dialog.plotInfo.qty,//20180418 modify by Dustdusk for 調整回傳數量，一律改為使用者輸入的數量
                            abnormal_detail:plotInfo.workstation_detail[0].abnormal_detail
                        }]
                    };

                    $MMWService.sendToServer({
                        uri: 'ServicesSTD.Module_WIP.production_parameters_check_process',
                            // $mddProvider.Getfunc('G0104Service', 'production_parameters_check_process'),
                        content: content,
                        success: function (data) {
                            checkRule(data.query_result, dialog);
                        }
                    });
                }

                //根據結果結果呈現
                //rule_result : WARNNING / WAIT / PASS
                //20170517 modify by Dustdusk for SMES_ProductionParametersCheckProcess調整回傳內容
                function checkRule(query_result, dialog){
                    var warnning_msg = '';
                    query_result.forEach(function(plot_rule){
                        var plot_warnning_msg = '';
                        plot_rule.rule_detail.forEach(function(rule_detail){
                            if(rule_detail.rule_result == 'WARNNING'){
                                if(plot_warnning_msg == ''){
                                    plot_warnning_msg = plot_rule.plot_no + '<br>';
                                }
                                plot_warnning_msg += rule_detail.rule_message + '<br>';
                            } else if(rule_detail.rule_result == 'WAIT'){
                                //is_wait = true;
                                dialog.plotInfo.wait_reason_detail.push({reason_no:'Z901'});
                            }
                        });
                        warnning_msg += plot_warnning_msg;
                    });

                    if(warnning_msg != ''){
                        $rootScope.showConfirm(warnning_msg,
                            function(dialog){
                                dialog.hide();
                                trackOutConfirm(dialog);
                            }
                        )
                    } else {
                        trackOutConfirm(dialog);
                    }
                }

                //取得例外原因類別
                function genBadType(badReasonList){
                    var badTypeList = [];
                    var badType = '';
                    badReasonList.forEach(function(badReason){
                        if(badType!=badReason.reason_type){
                            badTypeList.push({
                                reason_type:badReason.reason_type,
                                reason_sub_type:badReason.reason_sub_type
                            });
                            badType = badReason.reason_type;
                        }
                    });

                    return badTypeList;
                }

                //轉換率計算
                function CaculatQTYACIO(qty, C_Numerator, C_Denominator){
                    var QTYACIO = $calculater.decimalMutiple((+qty), (+C_Numerator)/(+C_Denominator)),
                        C_Mode = plotInfo.workstation_detail[0].C_Mode,
                        C_Accuracy = Math.pow(10,plotInfo.workstation_detail[0].C_Accuracy||0)||1;
                    if(C_Mode == '0'){
                        //無條件進位
                        QTYACIO = Math.ceil(QTYACIO * C_Accuracy) / C_Accuracy;
                    } else if(C_Mode == '1'){
                        //無條件捨位
                        QTYACIO = Math.floor(QTYACIO * C_Accuracy) / C_Accuracy;
                    }
                    return QTYACIO;
                }

                //模製具壽命檢查
                function SMES_AccLifeCheck(machine_no, plotInfo, callback){
                    var content = {
                        recordlist : [{
                            op_no : plotInfo.workstation_detail[0].op_no,
                            plot_no: plotInfo.workstation_detail[0].plot_no,
                            machine_no: machine_no,
                            status:'1',
                            qty : plotInfo.qty
                        }
                    ]};
                    $MMWService.sendToServer({
                        uri: 'ServicesSTD.Module_ACC.acc_life_check_process',
                            // $mddProvider.Getfunc('G0104Service', 'acc_life_check_process'),
                        content : content,
                        success : function(data){
                            if(data.life_manage == '0'){
                                //警示
                                $rootScope.showConfirm(data.description, function(confirmDialog){
                                    confirmDialog.hide();
                                    if(callback)
                                        callback();
                                });
                            } else if(data.life_manage == '1'){
                                //暫停生產
                                $rootScope.showAlert(data.description);
                            } else if(data.life_manage == '2'){
                                //核准
                                if(callback)
                                    callback();
                            }
                        }
                    });
                }

                //生產信息收集檢查
                function productionInfValidate(production_inf_detail){
                    var msg = '';
                    production_inf_detail.forEach(function(item){
                        if(item.productioninf_value == undefined || item.productioninf_value ==''){
                            msg +=$filter('translate')('G0104.msg.productioninf_value_empty', item)+'<br>';
                        }
                    });
                    return msg;
                }

                //開窗
                var openDialog = function (plotInfo) {
                    //test
                    plotInfo.rule_yield_ls = 87;
                    plotInfo.rule_yield_lcl = 78;
                    //console.log(plotInfo.rule_yield_ls != '' || plotInfo.rule_yield_lcl != '');
                    plotInfo.wait_reason_detail = [];
                    
                        $mdDialog.dialog(
                            'module/moduleG/program/G01/G0104/G0104.html',
                            function (dialog) {
                                return {
                                    G0104Service_BadReason_List: [],
                                    _fn: {
                                        'badReason': {
                                            click: () => {
                                                dialog.openBadPage();
                                            }
                                        },
                                        'G0104Service_G0104Service_BadReason': {
                                            click: function () {                                                
                                                dialog.changeForm('G0104Service_BadReason');
                                                dialog.openBadPage();
                                            }
                                        },
                                        'G0104Service_BadReason_Add': {
                                            click: () => {
                                                dialog.addBadReason();
                                            }
                                        },
                                        'G0104Service_Multiple_Add': {
                                            click: () => {
                                                dialog.searchLabor();
                                            }
                                        },
                                        'G0104Service_G0104Service_Multiple': {
                                            click: () => {                                                
                                                dialog.changeForm('G0104Service_Multiple');
                                                dialog.plotInfo.workstation_detail[0].labor_detail = angular.merge([], dialog.plotInfo.workstation_detail[0].labor_detail);
                                                dialog.G0104Service_Multiple_List = dialog.plotInfo.workstation_detail[0].labor_detail;
                                            }
                                        },
                                        'G0104Service_BadReason_Execute': {
                                            click: () => {
                                                dialog.badReasonConfirm();
                                            }
                                        },
                                        'G0104Service_Multiple_Execute': {
                                            click: () => {
                                                dialog.multipleConfirm();
                                            }
                                        },
                                        'G0104Service_Execute': {
                                            click: () => {
                                                dialog.trackOutConfirm();
                                            }
                                        }
                                    },
                                    _event: {
                                        //dialog._event['G0104Service_qty'].click(dialog.plotInfo.qty, {event:$event});
                                        'G0104Service_qty': {
                                            click: (qty, event) => {
                                                dialog.trackOutInputQty(event, qty);
                                            }
                                        },
                                        'plotInfo.qty': {
                                            click: (qty ,event) => {
                                                dialog.trackOutInputQty(event, qty);
                                            }
                                        },
                                        'plotInfo.machine_no_wip_display': {
                                            click: ( ) => {
                                                dialog.loadMachineList();
                                            }
                                        },
                                        //dialog._event['G0104Service_BadReason_reason_name'].click(dialog.tmpBadReason.reason_name, {event:$event});
                                        'G0104Service_BadReason_reason_name': {
                                            click: () => {
                                                dialog.loadBadReasonList();
                                            }
                                        },
                                        // 20230209 modify by Alan for #127256: 補上顯示卡控
                                        'G0104Service_slot_price_type_name': {
                                            isShown: plotInfo.is_opm
                                        },
                                        'G0104Service_slot_price': {
                                            isShown: plotInfo.is_opm
                                        },
                                        'G0104Service_slot_price_sum': {
                                            isShown: plotInfo.is_opm
                                        },
                                        'G0104Service_slot_machine_no_wip_display': {
                                            isShown: record_eqp,
                                            click: () => dialog.loadMachineList(),
                                            change: (value, event) => {
                                                if(event.event.keyCode == '13') dialog.loadMachineList()
                                            }
                                        },
                                        'G0104Service_slot_machine_hours': {
                                            isShown: record_eqp,
                                            // click: (hours, args) => {
                                            //     var target = args.event.currentTarget;
                                            //     angular.element(target).addClass('is-focus');
                                            //     $calculater.open(function(num,calcDialog){
                                            //         calcDialog.hide();
                                            //         angular.element(target).removeClass('is-focus');
                                            //         dialog.G0104Service_slot_machine_hours = num;
                                            //     },
                                            //     function(calcDialog){
                                            //         angular.element(target).removeClass('is-focus');
                                            //         calcDialog.hide();
                                            //     },
                                            //     {
                                            //         defaultNum : hours,
                                            //         decimal : true
                                            //     });
                                            // }
                                        },
                                        'dialog.G0104Service_Multiple_List.qty': {
                                            click: (qty, args) => {
                                                // dialog.laborInputQty(args.event, qty)
                                                var target = args.event.currentTarget;
                                                angular.element(target).addClass('is-focus');
                                                $calculater.open(function(num,calcDialog){
                                                    if((+num) > (+dialog.plotInfo.qty)){
                                                        $rootScope.showAlert($filter('translate')('G0104.showAlert.column6')+dialog.plotInfo.qty);
                                                    } else {
                                                        calcDialog.hide();
                                                        angular.element(target).removeClass('is-focus');
                                                        qty = num;
                                                        dialog.G0104Service_Multiple_List[args.index].qty = num;
                                                        getPriceSumByLabor();
                                                    }
                                                },
                                                function(calcDialog){
                                                    angular.element(target).removeClass('is-focus');
                                                    calcDialog.hide();
                                                },
                                                {
                                                    defaultNum : qty,
                                                    decimal : true
                                                });
                                            }
                                        },
                                        'dialog.G0104Service_Multiple_List.labor_time': {
                                            click: (labor_time, args) => {
                                                var target = args.event.currentTarget;
                                                angular.element(target).addClass('is-focus');
                                                $calculater.open(function (num, calcDialog) {
                                                    calcDialog.hide();
                                                    angular.element(target).removeClass('is-focus');
                                                    dialog.G0104Service_Multiple_List[args.index].labor_time = num;
                                                    getPriceSumByLabor();
                                                },
                                                    function (calcDialog) {
                                                        angular.element(target).removeClass('is-focus');
                                                        calcDialog.hide();
                                                    },
                                                    {
                                                        defaultNum: labor_time,
                                                        decimal: true
                                                    });
                                            }
                                        },
                                        'dialog.G0104Service_Multiple_List.price_type_name': {
                                            isShown: plotInfo.is_opm
                                        },
                                        'dialog.G0104Service_Multiple_List.price': {
                                            isShown: plotInfo.is_opm
                                        },
                                        'dialog.G0104Service_Multiple_List.price_sum': {
                                            isShown: plotInfo.is_opm
                                        }
                                    },
                                    css_url: 'JSplugins/angular-material-lite/template/dynamicService.tmp.css',
                                    isRequire: plotInfo.production_inf_type == '2',
                                    plotInfo: plotInfo,
                                    mode: mode,
                                    badCodeList: badCodeList,
                                    tmpBadReason: tmpBadReason,
                                    tmpAbnormal_qty: tmpAbnormal_qty,
                                    badReasonInfo: plotInfo.workstation_detail[0].abnormal_detail,
                                    parent: parent,
                                    backToTrackOut: backToTrackOut,//返回出站報工畫面
                                    tmpLabor_no: '',
                                    record_eqp: record_eqp, //是否紀錄生產設備及機時
                                    showRuleYield: function () {
                                        return dialog.plotInfo.rule_yield_ls != '' || dialog.plotInfo.rule_yield_lcl != '';
                                    },
                                    trackOutInputQty: function (event, trackOutQty) {
                                        var target = event.currentTarget;
                                        angular.element(target).addClass('is-focus');
                                        $calculater.open(function (num, calcDialog) {
                                            //20190919 modify by dustdusk for M#62326: 報工數量允許為0
                                            if ((+num) > dialog.plotInfo.workstation_detail[0].check_out_qty) {
                                                $rootScope.showAlert($filter('translate')('G0104.msg.column1') + num + $filter('translate')('G0104.msg.column2') + dialog.plotInfo.workstation_detail[0].check_out_qty);
                                            } else {
                                                dialog.plotInfo.qty = num;

                                                //dialog.plotInfo.good_qty = num;
                                                if ((+num) != trackOutQty) {
                                                    //2018051601 modify by Dustdusk for M#45925:
                                                    //物料使用量 = 『良品』 + 『不良品』 + 『短少』 = 『出站數量』 + 『多餘』
                                                    var sum_qty = $calculater.decimalAdd((+dialog.plotInfo.qty), (+dialog.plotInfo.total_surplus_qty));
                                                    for (var i = 0; i < plotInfo.workstation_detail[0].materials_detail.length; i++) {
                                                        plotInfo.workstation_detail[0].materials_detail[i].use_qty =
                                                            $calculater.decimalMutiple(sum_qty, plotInfo.workstation_detail[0].materials_detail[i].std_use_qty, 6);
                                                    }
                                                    //多人產量登入
                                                    for (var i = 0; i < plotInfo.workstation_detail[0].labor_detail.length; i++) {
                                                        //2021030301 modify by 智翔 for M#88057:子作业数量异常
                                                        plotInfo.workstation_detail[0].labor_detail[i].qty = num;
                                                        //if((+plotInfo.workstation_detail[0].labor_detail[i].qty)>num){
                                                        //    plotInfo.workstation_detail[0].labor_detail[i].qty = num;
                                                        //}
                                                    }

                                                    //2018051601 modify by Dustdusk for M#45925:
                                                    //如果良品數 = 『出站數量』 - 『不良品』 - 『短少』 + 『多餘』 小於0則清空例外原因
                                                    if (((+num) + dialog.plotInfo.total_surplus_qty) < ((+dialog.plotInfo.total_abnormal_qty) + (+dialog.plotInfo.total_lack_qty))) {
                                                        var total_abnormal_qty = dialog.plotInfo.total_abnormal_qty;
                                                        var total_surplus_qty = dialog.plotInfo.total_surplus_qty;
                                                        var total_lack_qty = dialog.plotInfo.total_lack_qty;
                                                        dialog.plotInfo.total_abnormal_qty = 0;
                                                        dialog.plotInfo.total_surplus_qty = 0;
                                                        dialog.plotInfo.total_lack_qty = 0;
                                                        dialog.badReasonInfo = [];
                                                        dialog.plotInfo.good_qty = num;
                                                        dialog.plotInfo.workstation_detail[0].QTYACIO = CaculatQTYACIO(dialog.plotInfo.good_qty, dialog.plotInfo.workstation_detail[0].C_Numerator, dialog.plotInfo.workstation_detail[0].C_Denominator);
                                                        $rootScope.showAlert($filter('translate')('G0104.msg.qty_less_than_abnormal_qty', { abnormal_qty: (total_abnormal_qty + total_lack_qty - total_surplus_qty) }));
                                                    } else {
                                                        //2018051601 modify by Dustdusk for M#45925:
                                                        //良品數 = 『出站數量』 - 『不良品』 - 『短少』 + 『多餘』
                                                        dialog.plotInfo.good_qty = $calculater.decimalSub($calculater.decimalSub($calculater.decimalAdd((+num), (+dialog.plotInfo.total_surplus_qty)), (+dialog.plotInfo.total_abnormal_qty)), (+dialog.plotInfo.total_lack_qty));
                                                        dialog.plotInfo.workstation_detail[0].QTYACIO = CaculatQTYACIO(dialog.plotInfo.good_qty, dialog.plotInfo.workstation_detail[0].C_Numerator, dialog.plotInfo.workstation_detail[0].C_Denominator);
                                                    }
                                                }
                                                calcDialog.hide();
                                                angular.element(target).removeClass('is-focus');
                                                //人員計價 出站 總額計算 add by a991241234 for M# 70310
                                                getPriceSum();
                                                getPriceSumByLabor();
                                            }
                                        },
                                            function (calcDialog) {
                                                angular.element(target).removeClass('is-focus');
                                                calcDialog.hide();
                                            },
                                            {
                                                defaultNum: trackOutQty,
                                                decimal: true
                                            });

                                    },
                                    trackOutBack: function () {
                                        dialog.hide();
                                        if (feedback)
                                            feedback();
                                    },
                                    //出站確認
                                    trackOutConfirm: function () {
                                        if (dialog.isRequire) {
                                            $rootScope.showAlert($filter('translate')('G0104.msg.production_inf_require'), function () {
                                                dialog.openProductionInfPage();
                                            });
                                        } else if (dialog.plotInfo.good_qty < 0) {
                                            $rootScope.showAlert($filter('translate')('G0104.msg.good_qty_less_than_zero'));
                                        } else {
                                            // SMES_AccLifeCheck(machine_no, dialog.plotInfo, function(){
                                            //     ProductionParametersCheckProcess(dialog);
                                            // });
                                            trackOutConfirm(dialog);
                                        }
                                    },
                                    //開啟不良原因
                                    openBadPage: function () {
                                        var content = {
                                            op_no: dialog.plotInfo.workstation_detail[0].op_no
                                        };
                                        $MMWService.sendToServer({
                                            uri: 'ServicesSTD.Module_WIP.qc_reason_basis_info_get',
                                                // $mddProvider.Getfunc('G0104Service', 'qc_reason_basis_info_get'),
                                            content: content,
                                            success: function (data, response) {
                                                if (data.Result != 'fail') {
                                                    dialog.badTypeList = genBadType(data.qc_reason_basis);
                                                    badCodeList = data.qc_reason_basis;
                                                    dialog.mode = 'badReason';
                                                    dialog.tmpBadReason = {};
                                                    dialog.tmpBadType = '';
                                                    dialog.tmpBadType_display = '';
                                                    dialog.tmpBadTypeName = '';
                                                    dialog.tmpAbnormal_qty = '';
                                                    //備份當時的不明原因列表
                                                    badReasonInfo_backup = dialog.badReasonInfo.slice();
                                                } else {
                                                    $rootScope.showAlert(response.Message);
                                                }
                                            }
                                        });
                                    },
                                    loadBadTypeList: function () {
                                        $rootScope.showSelect({
                                            label: 'reason_sub_type',
                                            code: 'reason_type',
                                            selectCode: dialog.tmpBadType,
                                            list: dialog.badTypeList,
                                            confirm: function (item, radioDialog) {
                                                radioDialog.hide();
                                                dialog.tmpBadType = item.reason_type;
                                                dialog.tmpBadTypeName = item.reason_sub_type;
                                            }
                                        });
                                    },
                                    loadBadReasonList: function () {
                                        if (dialog.tmpBadType != '') {
                                            $rootScope.showQueryList({
                                                key: 'reason_no',
                                                title: $filter('translate')('common.queryList.badReason_select'),
                                                header: [
                                                    { label: $filter('translate')('common.queryList.reason_c'), code: 'reason_no' },
                                                    { label: $filter('translate')('common.queryList.reason_n'), code: 'reason_name' }
                                                ],
                                                query: function (conditions, feedback) {
                                                    feedback($filter('filter')(badCodeList, { reason_type: dialog.tmpBadType }));
                                                },
                                                confirm: function (selectItem, radioDialog) {
                                                    radioDialog.hide();                                                    
                                                    dialog.tmpBadReason = selectItem;
                                                    dialog.tmpBadReason.reason_name = selectItem.reason_name;                                                    
                                                }
                                            });
                                        } else {
                                            $rootScope.showAlert($filter('translate')('G0104.msg.bad_type_empty'));
                                        }
                                    },
                                    //新增不良原因
                                    addBadReason: function () {
                                        if (!dialog.tmpBadReason.reason_name) {
                                            $rootScope.showAlert($filter('translate')('G0104.showAlert.column3'), function () {
                                                dialog.tmpBadType = '';
                                                dialog.tmpBadTypeName = '';
                                                dialog.tmpBadReason = {};
                                                dialog.tmpAbnormal_qty = '';
                                            });
                                        } else {
                                            if (dialog.tmpAbnormal_qty > 0) {
                                                dialog.badReasonInfo.push({
                                                    plot_no: dialog.plotInfo.workstation_detail[0].plot_no,
                                                    abnormal_type: dialog.tmpBadReason.reason_type,
                                                    abnormal_type_name: dialog.tmpBadReason.reason_sub_type,
                                                    abnormal_no: dialog.tmpBadReason.reason_no,
                                                    abnormal_name: dialog.tmpBadReason.reason_name,
                                                    defect_qty: dialog.tmpAbnormal_qty,
                                                });
                                                
                                                //dialog.G0104Service_BadReason_List = dialog.badReasonInfo;
                                                
                                                dialog.tmpBadType = '';
                                                dialog.tmpBadTypeName = '';
                                                dialog.tmpBadReason = {};
                                                dialog.tmpAbnormal_qty = '';
                                                dialog.tmpBadType_display = '';
                                                console.log(dialog.badReasonInfo);
                                                /*console.log(dialog.G0104Service_BadReason_List);*/
                                            } else {
                                                $rootScope.showAlert($filter('translate')('G0104.showAlert.column4'), function () {
                                                    dialog.tmpAbnormal_qty = '';
                                                });
                                            }
                                        }
                                    },
                                    //刪除不良原因
                                    removeBadReason: function (item) {
                                        dialog.badReasonInfo.splice(dialog.badReasonInfo.indexOf(item), 1);
                                    },
                                    //不良原因-確定
                                    badReasonConfirm: function () {
                                        var total_surplus_qty = 0;//多餘數
                                        var total_abnormal_qty = 0; //報廢
                                        var total_lack_qty = 0;//短少
                                        dialog.badReasonInfo.forEach(function (info) {
                                            if (info.abnormal_type == '11') {
                                                total_surplus_qty = $calculater.decimalAdd(total_surplus_qty, (+info.defect_qty));
                                            } else if (info.abnormal_type == '12') {
                                                total_lack_qty = $calculater.decimalAdd(total_lack_qty, (+info.defect_qty));
                                            } else {
                                                total_abnormal_qty = $calculater.decimalAdd(total_abnormal_qty, (+info.defect_qty));
                                            }
                                        });
                                        if ((total_surplus_qty + dialog.plotInfo.qty) < (total_abnormal_qty + total_lack_qty)) {
                                            $rootScope.showAlert($filter('translate')('G0104.showAlert.column5') + dialog.plotInfo.qty);
                                        } else {
                                            dialog.plotInfo.total_surplus_qty = total_surplus_qty;//多餘數
                                            dialog.plotInfo.total_abnormal_qty = total_abnormal_qty; //報廢
                                            dialog.plotInfo.total_lack_qty = total_lack_qty;//短少
                                            //2018051601 modify by Dustdusk for M#45925:
                                            //物料使用量 = 『良品』 + 『不良品』 + 『短少』 = 『出站數量』 + 『多餘』
                                            var sum_qty = $calculater.decimalAdd((+dialog.plotInfo.qty), (+dialog.plotInfo.total_surplus_qty));
                                            for (var i = 0; i < plotInfo.workstation_detail[0].materials_detail.length; i++) {
                                                plotInfo.workstation_detail[0].materials_detail[i].use_qty =
                                                    $calculater.decimalMutiple(sum_qty, plotInfo.workstation_detail[0].materials_detail[i].std_use_qty, 6);
                                            }
                                            //2018051601 modify by Dustdusk for M#45925:
                                            //良品數 = 『出站數量』 - 『不良品』 - 『短少』 + 『多餘』
                                            dialog.plotInfo.good_qty = $calculater.decimalSub($calculater.decimalSub($calculater.decimalAdd((+dialog.plotInfo.qty), (+dialog.plotInfo.total_surplus_qty)), (+dialog.plotInfo.total_abnormal_qty)), (+dialog.plotInfo.total_lack_qty));
                                            dialog.plotInfo.workstation_detail[0].QTYACIO = CaculatQTYACIO(dialog.plotInfo.good_qty, dialog.plotInfo.workstation_detail[0].C_Numerator, dialog.plotInfo.workstation_detail[0].C_Denominator);
                                            dialog._nowForm = 'G0104Service';
                                        }

                                    },
                                    //不良原因，取消
                                    badReasonCancel: backToTrackOut,

                                    //進入多人產量登入
                                    openMultiplePage: function () {
                                        dialog.mode = 'multiple';
                                        labor_detail_backup = angular.merge([], dialog.plotInfo.workstation_detail[0].labor_detail);
                                    },
                                    addMultipleLabor: function (labor_no, labor_name) {
                                        var labor_detail = dialog.plotInfo.workstation_detail[0].labor_detail;
                                        var isExist = false;
                                        for (var i = 0; i < labor_detail.length; i++) {
                                            if (labor_detail[i].labor_no == labor_no) {
                                                isExist = true;
                                                break;
                                            }
                                        }
                                        if (!isExist) {
                                            labor_detail.push({ labor_no: labor_no, labor_name: labor_name, qty: plotInfo.qty, labor_time: 0 });
                                        } else {
                                            $rootScope.showAlert($filter('translate')('G0104.msg.labor_no_exist', { labor_no: labor_no })); //人員已存在
                                        }
                                        dialog.tmpLabor_no = '';
                                        getPriceSum();
                                        getPriceSumByLabor();
                                    },
                                    deleteMultipleLabor: function (item) {
                                        $rootScope.showConfirm($filter('translate')('G0104.msg.is_delete_multiple_labor', { labor_name: item.labor_name }),
                                            function (confirmDialog) {
                                                confirmDialog.hide();
                                                var index = dialog.plotInfo.workstation_detail[0].labor_detail.indexOf(item);
                                                dialog.plotInfo.workstation_detail[0].labor_detail.splice(index, 1);
                                                getPriceSum();
                                                getPriceSumByLabor();
                                            }
                                        );
                                    },
                                    searchLabor: function (event) {
                                        if (!event || event.keyCode == 13) {
                                            if (dialog.tmpLabor_no != '') {
                                                var content = {
                                                    machine_no: machine_no,
                                                    employee_no: dialog.tmpLabor_no,
                                                    report_datetime: new Date(),
                                                    return_type: '10'
                                                };

                                                $MMWService.sendToServer({
                                                    uri: 'ServicesSTD.Module_SYS.user_information_get',
                                                        // $mddProvider.Getfunc('G0104Service', 'user_information_get'),
                                                    content: content,
                                                    success: function (data) {
                                                        dialog.addMultipleLabor(data.employee_no, data.employee_name);
                                                    },
                                                    error: function (data) {
                                                        $rootScope.showAlert(data.Message, function () {
                                                            document.getElementById('tmpLabor_no').focus();
                                                        });
                                                    }
                                                });
                                            } else {
                                                $rootScope.showAlert($filter('translate')('G0104.msg.input_labor_empty'), function () {
                                                    document.getElementById('tmpLabor_no').focus();
                                                });
                                            }
                                        }
                                    },
                                    laborInputQty: function (event, labor) {
                                        var target = event.currentTarget;
                                        angular.element(target).addClass('is-focus');
                                        $calculater.open(function (num, calcDialog) {
                                            if ((+num) > (+dialog.plotInfo.qty)) {
                                                $rootScope.showAlert($filter('translate')('G0104.showAlert.column6') + dialog.plotInfo.qty);
                                            } else {
                                                calcDialog.hide();
                                                angular.element(target).removeClass('is-focus');
                                                labor.qty = num;
                                                getPriceSumByLabor();
                                            }
                                        },
                                            function (calcDialog) {
                                                angular.element(target).removeClass('is-focus');
                                                calcDialog.hide();
                                            },
                                            {
                                                defaultNum: labor.qty,
                                                decimal: true
                                            });
                                    },
                                    laborInputTime: function (event, labor) {
                                        var target = event.currentTarget;
                                        angular.element(target).addClass('is-focus');
                                        $calculater.open(function (num, calcDialog) {
                                            calcDialog.hide();
                                            angular.element(target).removeClass('is-focus');
                                            labor.labor_time = num;
                                            getPriceSumByLabor();
                                        },
                                            function (calcDialog) {
                                                angular.element(target).removeClass('is-focus');
                                                calcDialog.hide();
                                            },
                                            {
                                                defaultNum: labor.labor_time,
                                                decimal: true
                                            });
                                    },
                                    multipleCheck: function () {
                                        var msg = '';
                                        var labor_detail = dialog.plotInfo.workstation_detail[0].labor_detail;
                                        if (labor_detail.length == 0) {
                                            msg = $filter('translate')('G0104.msg.labor_detail_empty'); //人員明細不可為空
                                        } else {
                                            for (var i = 0; i < labor_detail.length; i++) {
                                                if (labor_detail[i].labor_time == 0 && labor_detail[i].qty == 0) {
                                                    msg = $filter('translate')('G0104.msg.qty_and_labor_time_is_empty'); //數量與人時不可同時為0。
                                                    break;
                                                }
                                            }
                                        }
                                        return msg;
                                    },
                                    multipleConfirm: function () {
                                        var msg = dialog.multipleCheck();
                                        if (msg == '') {
                                            //計算總人時
                                            dialog.plotInfo.workstation_detail[0].labor_hours = 0;
                                            dialog.plotInfo.workstation_detail[0].number_of_labor = 0;
                                            dialog.plotInfo.workstation_detail[0].labor_detail.forEach(function (labor) {
                                                dialog.plotInfo.workstation_detail[0].labor_hours = $calculater.decimalAdd(dialog.plotInfo.workstation_detail[0].labor_hours, labor.labor_time);
                                                dialog.plotInfo.workstation_detail[0].number_of_labor += 1;
                                            });
                                            dialog._nowForm = 'G0104Service';
                                        } else {
                                            $rootScope.showAlert(msg);
                                        }
                                    },
                                    multipleCancel: backToTrackOut,
                                    //進入生產資訊收集
                                    openProductionInfPage: function () {
                                        if (dialog.plotInfo.production_inf_detail && dialog.plotInfo.production_inf_detail.length > 0) {
                                            dialog.mode = 'production_inf';
                                            dialog.production_inf_detail = dialog.plotInfo.production_inf_detail;
                                            production_inf_detail_backup = angular.merge([], dialog.plotInfo.production_inf_detail);
                                        } else {
                                            $rootScope.showAlert($filter('translate')('G0104.showAlert.production_inf_detail_empty'));
                                        }
                                    },
                                    switchInit: function (item) {
                                        if (!item.productioninf_value) {
                                            item.productioninf_value = '0';
                                        }
                                    },
                                    switchClick: function (item) {
                                        if (item.productioninf_value == '0') {
                                            item.productioninf_value = '1';
                                        } else {
                                            item.productioninf_value = '0';
                                        }
                                    },
                                    productionInfConfirm: function () {
                                        var msg = '';
                                        if (dialog.plotInfo.production_inf_type == '2') {
                                            msg = productionInfValidate(dialog.production_inf_detail);
                                        }
                                        if (msg == '') {
                                            dialog.isRequire = false;
                                            dialog.mode = 'trackOut';
                                        } else {
                                            dialog.isRequire = true;
                                            $rootScope.showAlert(msg);
                                        }
                                    },
                                    loadMachineList: function () {
                                        //設備清單
                                        $rootScope.showQueryList({
                                            pageRecord: 25,
                                            header: [
                                                { label: $filter('translate')('common.queryList.machine_c'), code: 'page_no' },
                                                { label: $filter('translate')('common.queryList.machine_n'), code: 'page_name' }
                                            ],
                                            query: function (conditions, feedback) {
                                                $MMWService.pageNumberInfoGet({
                                                    //page_mode: 37,
                                                    form_name: 'PageNo_30',
                                                    query_condition_info: [
                                                        { column_name: 'OPNo', query_mode: '2', value: dialog.plotInfo.workstation_detail[0].op_no }
                                                    ]
                                                }, function (data) {
                                                    if (data && data.length) {
                                                        feedback(data);
                                                    }
                                                });
                                            },
                                            selectCode: dialog.plotInfo.machine_no_wip || '',
                                            confirm: function (selectItem, queryDialog) {
                                                dialog.plotInfo.machine_no_wip = selectItem.page_no;
                                                dialog.plotInfo.machine_no_wip_display = selectItem.page_no + '(' + selectItem.page_name + ')';
                                                // 20230209 modify by Alan for #127256: 補上顯示卡控
                                                dialog.G0104Service_slot_machine_no_wip_display = dialog.plotInfo.machine_no_wip_display;
                                                queryDialog.hide();
                                            }
                                        });
                                    }
                                };
                            }
                        );
                    
                    
                };
                $mddProvider.UseForm('G0104Service', () => {
                    getInitInfo();
                })
            };
        }]);
});
